import React, {Component} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    DeviceEventEmitter, FlatList, ActivityIndicator,
} from 'react-native';

import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Header from '../../components/header';
import Loading from '../../utils/Loading';
import NoData from '../../utils/NoData';
import {getCarRegisterDate, getImgUrl, getMileFormat, getPriceFormat} from '../../utils/ComFunction';
import AlertCommonView from "../../components/Tool/AlertCommonView";
import {ToastToUser} from "../../utils/CustomToast";
import SeekItemView from "./seekComponents/SeekItemView";
import Constant from "../../utils/Constant";
import AsyncImage from "../../components/image/AsyncImage";

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

let navigation;

export default class SeekingDetailPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // 弹窗
            showAlertCommonView: false,
            showAlertData: {},
            deleteId: null,
            upCarPurchaseId: null, // 当前上下架id

            seekingDetail: {},

            // 匹配到的列表
            carList: [],
            pageNo: 1,
            isRefresh: false,
            showFoot: 0,
            totalSize: this.props.route.params.carMatchCount || 0,
        };
    }

    componentDidMount() {
        this.SeekingDetailPage = DeviceEventEmitter.addListener('ApplyCarFormPageSave', (data) => {
            if(data.fromPage === 'SeekingDetailPage'){
                this.getData()
            }
        })
        this.getData()
        this.refreshData()
    }

    componentWillUnmount() {
        if (this.SeekMoreFilterPage) { // 移除筛选条件监听
            this.SeekMoreFilterPage.remove();
        }
    }


    // 删除求购
    deleteCarPurchase(){
        let routeData = this.props.route.params;
        let param = {
            id: routeData.id ? routeData.id : null,
        };
        HttpUtils.postRequest(HttpUrls.deleteCarPurchase, param).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("删除成功")
                navigation.goBack()
                DeviceEventEmitter.emit('ApplyCarFormPageSave', {
                    fromPage: 'BuyerDetailPage',
                })
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    upCarPurchase(){
        console.log('upCarPurchase', '上架')
        let routeData = this.props.route.params;
        let param = {
            id: routeData.id ? routeData.id : null,
        };
        HttpUtils.postRequest(HttpUrls.upCarPurchase, param).then(result => {
            if(result.code === 0){
                console.log(result)
                ToastToUser("上架成功")
                this.getData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    downCarPurchase(){
        console.log('upCarPurchase', '下架')
        let routeData = this.props.route.params;
        let param = {
            id: routeData.id ? routeData.id : null,
        };
        HttpUtils.postRequest(HttpUrls.downCarPurchase, param).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("下架成功")
                this.getData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title="我的求购详情" />

                {this.state.seekingDetail && Object.keys(this.state.seekingDetail).length > 0 ? (
                    <SeekItemView
                        item={this.state.seekingDetail}
                        buyerId={Constant.userInfo.buyerId}
                        navigation={navigation}
                        isDetail={true}
                        onPressDel={() => {
                            this.setState({
                                deleteId: this.state.seekingDetail.id,
                                showAlertData: {
                                    title: '确定删除求购信息?',
                                    cancelBtnText: '取消',
                                    sureBtnText: '确定',
                                    type: 'delete'
                                },
                                showAlertCommonView: true,
                            })
                        }}
                        onPressUpDown={() => {
                            if(this.state.seekingDetail.status === 1){ // 进行下架操作
                                this.setState({
                                    upCarPurchaseId: this.state.seekingDetail.id,
                                    showAlertData: {
                                        title: '确定下架求购信息?',
                                        cancelBtnText: '取消',
                                        sureBtnText: '确定',
                                        type: 'down'
                                    },
                                    showAlertCommonView: true,
                                })
                            }else if (this.state.seekingDetail.status === 2 || this.state.seekingDetail.status === 3) { // 上架操作
                                this.setState({
                                    upCarPurchaseId: this.state.seekingDetail.id,
                                    showAlertData: {
                                        title: '确定上架求购信息?',
                                        cancelBtnText: '取消',
                                        sureBtnText: '确定',
                                        type: 'up'
                                    },
                                    showAlertCommonView: true,
                                })
                            }
                        }}
                        onPressEdit={() => {
                            navigation.navigate('ApplyCarFormPage', {
                                id: this.state.seekingDetail.id,
                                fromPage: 'SeekingDetailPage',
                            });
                        }}
                    ></SeekItemView>
                ): null}

                <Text style={{fontSize: 16, color: '#333', marginLeft: 15, marginTop: 15, marginBottom: 12}}>匹配车源</Text>
                {this.renderCarList()}

                {/* 弹窗提示 */}
                {
                    this.state.showAlertCommonView ?
                        <AlertCommonView
                            title={this.state.showAlertData.title}
                            content={this.state.showAlertData.content}
                            cancelBtnText={this.state.showAlertData.cancelBtnText}
                            sureBtnText={this.state.showAlertData.sureBtnText}
                            cancelHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                            }}
                            sureHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                                if (this.state.showAlertData.type === 'delete') {
                                    this.deleteCarPurchase()
                                }else if (this.state.showAlertData.type === 'up') { // 上架求购信息
                                    this.upCarPurchase()
                                }else if (this.state.showAlertData.type === 'down') { // 下架求购信息
                                    this.downCarPurchase()
                                }
                            }}
                        />
                        :
                        null
                }
                <Loading onRef={ref => (this.Loading = ref)} />
            </View>
        );
    }

    renderCarList() {
        return (
            <FlatList
                data={this.state.carList}
                renderItem={this.renderCarItem.bind(this)}
                keyExtractor={item => item.carId + ''}
                style={{ flex: 1 }}
                extraData={this.state}
                ListFooterComponent={this._renderFooter.bind(this)}
                ListEmptyComponent={this.renderEmpty.bind(this)}
                onEndReached={this._onEndReached.bind(this)}
                onEndReachedThreshold={0}
                onRefresh={this.refreshData}
                refreshing={this.state.isRefresh}
            />
        )
    }

    // 买方
    renderCarItem({ item, index }) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.cardContainer}
                activeOpacity={0.8}
                onPress={() => {
                    navigation.navigate('CarOfferPriceDetailPage', {
                        carId: item.carId,
                        saleStatus: item.saleStatus,
                        merchantId: item.merchantId
                    })
                    // navigation.navigate('CarOfferPricePage',{carId:item.carId,merchantId:item.merchantId})
                }}
            >
                <View style={styles.itemCompanyContain}>
                    <Text style={styles.companyText}>{item.merchantAbbreviation}</Text>
                    <Text style={styles.companyText}>{this.getQuotationProgressStatus(item)}</Text>
                </View>

                <View style={{ backgroundColor: '#f6f6f6', height: 1 }}></View>

                <View style={styles.carContainer}>

                    <AsyncImage
                        source={{ uri: getImgUrl(item.mainPic) }}
                        defaultSource={require('source/image/icon_car_default.png')}
                        style={styles.carImage}
                        resizeMode="cover"
                    />

                    <View style={styles.infoContainer}>
                        <View>
                            <Text style={styles.carName} numberOfLines={2} ellipsizeMode='tail'>{item.seriesName + ' ' + item.speciesName}</Text>

                            <Text style={styles.subInfo}>
                                {this.getSubCarInfo(item)}
                            </Text>
                        </View>


                        <View style={styles.priceContain}>
                            <Text style={styles.price}>挂牌价：{getPriceFormat(item.listPrice)}</Text>

                            {item.conversationQuantity && item.conversationQuantity != 0 ?
                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    {/*<Image style={styles.msgCountImg} source={require('source/image/car/icon_car_msg.png')}></Image>*/}
                                    <Text style={{color: '#999999'}}>{item.conversationQuantity}人</Text>
                                </View>
                                :
                                null
                            }

                        </View>

                        <View>
                            <Text style={{fontSize: 12, color: '#999999'}}>{item.createTime}</Text>
                        </View>


                    </View>
                </View>
            </TouchableOpacity>
        )

    }

    getSubCarInfo(item) {

        if (item.carType == 1) {//新车

            return '新车指导价：' + getPriceFormat(item.guidePrice)
        } else {
            return getCarRegisterDate(item.registerDate) + ' ' + getMileFormat(item.mileage)
        }
    }

    getQuotationProgressStatus(item) {
        console.log('quotationProgressStatus', item.quotationProgressStatus)
        if (item.quotationProgressStatus == 1) {
            return (
                <View style={{flexDirection: 'row'}}>
                    {/*<Text style={{backgroundColor: '#FFFBE8', fontSize: 12, paddingHorizontal: 5, paddingVertical: 2, borderRadius: 2, color: '#ED542E'}}>{item.timeoutTimeShowStr || ''}</Text>*/}
                    <Text style={{color: '#ED542E', marginLeft: 4}}>待处理</Text>
                </View>
            )
        } else if (item.quotationProgressStatus == 2) {
            return '沟通中'
        } else if (item.quotationProgressStatus == 4) {
            return '待确认'
        }
        return ''
    }


    _renderFooter() {
        if (this.state.carList.length == 0) {
            return null;
        }
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        console.log('_onEndReached', this.state.showFoot)
        // 添加更严格的条件判断
        if (this.state.showFoot != 0 || this.state.carList.length === 0) {
            return null;
        }

        let nextPage = this.state.pageNo + 1

        this.setState({ showFoot: 2, pageNo: nextPage },
            function () {
                this.getCarList();
            });
    }

    renderEmpty() {
        return <NoData Desc="暂无数据" style={{marginTop: gREM(50)}} />;
    }

    refreshData = () => {

        this.setState({ carList: [], isRefresh: true, pageNo: 1 }, function () {
            this.getCarList();
        })

    }

    getCarList() {
        let routeData = this.props.route.params;
        let param = {
            pageNo: this.state.pageNo,
            pageSize: 50,
            carPurchaseId: routeData.id ? routeData.id : null,
        };

        console.log('resultsearchCars==param', param)

        HttpUtils.postRequest(HttpUrls.carPurchaseSearchCars, param)
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let resultList = result.data.resultList
                    if (resultList.length > 0) {
                        if (resultList.length < 20) {
                            this.setState({
                                showFoot: 1
                            })
                        } else {
                            this.setState({
                                showFoot: 0
                            })
                        }
                        this.setState({
                            carList: this.state.carList.concat(resultList),
                        })
                    } else {
                        this.setState({
                            showFoot: 1
                        })
                    }
                    this.setState({
                        isRefresh: false,

                    })
                } else {
                    this.setState({
                        isRefresh: false,

                    })
                }
            })
            .catch((error) => {
                this.setState({
                    isRefresh: false,
                })
            });
    }


    getData() {
        let routeData = this.props.route.params;
        let param = {
            id: routeData.id ? routeData.id : null,
        };
        this.Loading.show();
        HttpUtils.getRequest(HttpUrls.getCarPurchaseDetail, param)
            .then(result => {
                if(result.code === 0){
                    result.data.carMatchCount = this.state.totalSize;
                    this.setState({
                        seekingDetail: result.data
                    })
                }
            })
            .catch(error => {}).finally(() => {
            // this.getCarList();
            this.Loading.hide();
        });
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },

    itemContainer: {
        backgroundColor: '#fff',
        overflow: 'hidden',
        paddingHorizontal: 15,
        paddingVertical: 15,
    },
    itemHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
    },
    avatar: {
        width: 50,
        height: 50,
        borderRadius: 50,
        backgroundColor: '#cccccc',
        marginRight: 10,
    },
    headerTextContainer: {
        flex: 1,
    },
    userText: {
        fontSize: 14,
        color: '#333',
    },
    timeText: {
        color: '#888888',
        fontSize: 12,
    },
    consultationText: {
        color: '#888888',
        fontSize: 12,
    },
    titleText: {
        fontSize: 15,
        marginBottom: 10,
        color: '#333333',
    },
    contentText: {
        fontSize: 14,
        marginBottom: 10,
        lineHeight: 22,
    },
    detailText: {
        color: '#333333',
        marginBottom: 5,
        fontSize: 14,
    },
    listTagsContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 5,
        marginBottom: 10,
    },
    tag: {
        backgroundColor: '#fff399',
        borderRadius: 4,
        paddingVertical: 4,
        paddingHorizontal: 8,
        marginRight: 5,
        marginBottom: 5,
        // borderWidth: 1,
        // borderColor: '#e0e0e0',
    },
    tagText: {
        fontSize: 12,
        color: '#333333',
    },

    actionsContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
    },
    actionButton: {
        flexDirection: 'row',
        padding: 5,
    },
    actionButtonText: {
        fontWeight: 'bold',
        fontSize: 14,
        color: '#333333',
        marginLeft: 5,
    },
    actionImage: {
        width: 20,
        height: 20,
    },

    // 车辆列表
    cardContainer: {
        backgroundColor: '#fff',
        paddingHorizontal: 15,
        paddingBottom: 15,
        marginTop: 10,
        flexDirection: 'column',
        width: '100%',
    },
    itemCompanyContain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        height: 44,
        alignItems: 'center'
    },
    companyText: {
        fontSize: 14,
        color: '#333333'
    },
    carContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
    },
    carImage: {
        width: 130,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#f5f5f5',
    },
    infoContainer: {
        flex: 1,
        marginLeft: 10,
        height: 90,
        flexDirection: 'column',
        justifyContent: 'space-between',
    },
    carName: {
        fontSize: 14,
        fontWeight: '500',
        marginBottom: 5,
        color: '#333',
    },
    subInfo: {
        fontSize: 12,
        color: '#999999',
        marginTop: 3,
    },
    price: {
        fontSize: 14,
        color: '#ED542E',
    },
    msgCountImg: {
        width: 20,
        height: 20
    },
    priceContain: {
        flexDirection: 'row',
        justifyContent: 'space-between'
    },

});
